package com.yuye.cloud.common.exception;

import com.yuye.cloud.common.model.Result;
import com.yuye.cloud.common.model.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.List;

/**
 * 异常通用处理
 *
 * @author xgf
 */
@ResponseBody
@Slf4j
//@RestControllerAdvice
public class DefaultExceptionAdvice {

    /**
     * IdempotencyException 幂等性异常
     * 返回状态码:200
     * @param e 幂等异常
     * @return Result 异常信息
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(IdempotencyException.class)
    public Result<Object> handleException(IdempotencyException e) {
        return ResultUtil.error(e.getMessage());
    }

    /**
     * 所有异常统一处理
     * 返回状态码:500
     * @param e 异常类
     * @return Result 异常信息
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public Result<Object> handleException(Exception e) {
        return defHandler("未知异常", e);
    }
    
//    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Object> handleValidationExceptions(MethodArgumentNotValidException ex) {
    	StringBuilder sb = new StringBuilder();
    	List<ObjectError> allErrors = ex.getBindingResult().getAllErrors();
    	
        allErrors.forEach((error) -> {
//            String fieldName = ((FieldError) error).getField();
//            String errorMessage = error.getDefaultMessage();
//            errors.put(fieldName, errorMessage);
            sb.append(error.getDefaultMessage()).append(";");
        });
        return  ResultUtil.error(sb.toString());//这里可以根据具体情况改变状态码
    }
    
    

    private Result<Object> defHandler(String msg, Exception e) {
        log.error(msg, e);
        return ResultUtil.error(msg);
    }
}
